
//
//  SystemMessageVC.m
//  bestkeep
//
//  Created by bj on 2016/11/17.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "SystemMessageVC.h"
#import "Masonry.h"
#import "SystemMessageCell.h"
#import "SystemMessageModel.h"
#import "SystemMessageCommon.h"
#import "MJRefresh.h"
#import "BKRefreshControl.h"
#import "Mediator+BKMy.h"
#import "Mediator+BKGD.h"
#import "Mediator+BKMyOrderDetail.h"
#import "BKMyCommon.h"
#import "ExceptionView.h"

@interface SystemMessageVC ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, copy) NSString *useId;
@property (nonatomic, assign) int pageSize;
@property (nonatomic, assign) int pageNo;
@property (nonatomic, strong) NSMutableArray *marr_data;
//@property (nonatomic, copy)   NSString *relatedIdStr;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) UIView *backindicatorView;
@property (nonatomic, strong) ExceptionView *exceptionView;
@end

@implementation SystemMessageVC
static NSString *systemMessageCellIdentifier = @"systemMessageCellIdentifier";


- (void)viewDidLoad {
    [super viewDidLoad];
    [self set_empty_unReadMessage];
    [self setProperty];
    [self createUI];
    [self requestData];
}

-(void)setProperty{
    self.title = @"系统通知";
    self.view.backgroundColor = [UIColor whiteColor];
    _marr_data = [[NSMutableArray alloc] init];
    _pageNo = 1;
    _pageSize = 10;
}

/*
 * 将未读消息数字置空
 */
-(void)set_empty_unReadMessage{
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    [userInfo.realm beginWriteTransaction];
    userInfo.unreadMessageNum = @"";
    [userInfo.realm commitWriteTransaction];
}

- (void)createUI {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
    }];
    [self.tableView registerClass:[SystemMessageCell class] forCellReuseIdentifier:systemMessageCellIdentifier];
    [self setUpRefresh];
}

- (void)setUpRefresh {
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    footer.stateLabel.textColor = LoadMoreDataTitleColor;
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color=IndictorViewColor;
    [footer addSubview:loadingView];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.automaticallyHidden = YES;
}

/*
 * 获取数据
 */
- (void)requestData {
    [self checkNetWorking];
}

/*
 * 检查网络
 */
-(void)checkNetWorking {
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self loadData];
        }
            break;
            
        default: {
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self requestData];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
            
            // [HUD showMessage:@"请检查您的网络"];
        }
            break;
    }
}

- (void)loadData {
    [BKIndicationView showInView:self.view];
    [SystemMessageCommon getSystemMessageListWithUserid:[NSString stringWithFormat:@"%d", 0] pagesize:_pageSize pageno:_pageNo mycallBack:^(id obj, NSError *error) {
        BOOL success = [obj[@"success"] boolValue];
        if (success) {
            if(self.exceptionView) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
            }
            NSDictionary *dict = obj[@"data"];
            NSArray *array = dict[@"rows"];
            int total = [dict[@"total"] intValue];
            int pageNo = [dict[@"pageno"] intValue];
            for (NSDictionary *data in array) {
                SystemMessageModel *model = [[SystemMessageModel alloc] init];
                model.relatedId = data[@"relatedId"];
                model.title = data[@"msgTitle"];
                model.time = data[@"sendDateStr"];
                model.detail = data[@"msgContent"];
                model.messageType = data[@"msgType"];
                model.relatedStatus = data[@"relatedStatus"];
                model.messageId = data[@"id"];
                [self.marr_data addObject:model];
            }
            if (self.marr_data.count == 0) {
                [self noSystemMessage];
            }
            int totalPageNumber = (total + _pageSize - 1) / _pageSize;
            if (pageNo >= totalPageNumber) {
                [_tableView.mj_footer setHidden:YES];
            }
        } else {
            if(!self.exceptionView && error) {
                self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeServerError];
                
                ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeServerError handler:^(ExceptionViewAction *action) {
                    [self requestData];
                }];
                [self.exceptionView addAction:retryAction];
                [self.exceptionView showInView:self.view];
            }
        }
        [BKIndicationView dismiss];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        [_tableView reloadData];
    }];
}

- (void)noSystemMessage{
    self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoData];
    ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoData handler:^(ExceptionViewAction *action) {
        [self.exceptionView dismiss];
        self.exceptionView = nil;
        [self requestData];
    }];
    [self.exceptionView addAction:action];
    [self.exceptionView showInView:self.view];
}

- (void)btnStartAnimation {
    _backindicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64)];
    _backindicatorView.backgroundColor = [UIColor clearColor];
    [self.view.window addSubview:_backindicatorView];
    _indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 70, 70)];
    _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [_indicatorView setCenter:CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2 - 30)];
    _indicatorView.color = RGBCOLOR(42, 187, 155, 1);
    _indicatorView.backgroundColor = [UIColor clearColor];
    _indicatorView.alpha = 1.0;
    CGAffineTransform transform = CGAffineTransformMakeScale(1.5f, 1.5f);
    _indicatorView.transform = transform;
    [_backindicatorView addSubview:_indicatorView];
    [_indicatorView startAnimating];
    [self requestData];
}

- (void)stopAnimation {
    [_indicatorView stopAnimating];
    [_indicatorView removeFromSuperview];
    [_backindicatorView removeFromSuperview];
}









- (void)refreshData {
    _pageNo = _pageNo + 1;
    [self requestData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.marr_data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SystemMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:systemMessageCellIdentifier];
    if (cell == nil) {
        cell = [[SystemMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:systemMessageCellIdentifier];
    }
    if (_marr_data.count < indexPath.row) {
        
    } else {
        cell.model = _marr_data[indexPath.row];
    }
    [cell.detailButton addTarget:self action:@selector(systemMessageCellButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.detailButton.tag = indexPath.row + 1;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_marr_data.count < indexPath.row) {
        return 0;
    } else {
        SystemMessageModel *model = _marr_data[indexPath.row];
        return model.cellHeight;
   }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SystemMessageModel *model = _marr_data[indexPath.row];
    [self pushVC:model];
}

- (void)systemMessageCellButtonClick:(UIButton *)sender {
    SystemMessageModel *model = _marr_data[sender.tag - 1];
    [self pushVC:model];
}



/*
 * <# say #>
 */
- (void)pushVC:(SystemMessageModel *)model {
    if ([model.messageType intValue] == 1) {
        UIViewController *vc = [[Mediator sharedInstance] GetBKMyOrderDetailController:model.relatedId];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if ([model.messageType intValue] == 2) {
        UIViewController *vc = [[Mediator sharedInstance] BKGD_goodsDetailViewController:model.relatedId saleTypes:nil];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if ([model.messageType intValue] == 3) {
        UIViewController *vc = [[Mediator sharedInstance] BK_couponViewController];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if ([model.messageType intValue] == 4){
        UIViewController *vc = [[Mediator sharedInstance] GetBKMyOrderDetailController:model.relatedId];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end























